<?php
class imageUpload{

	public $opath;//原图存放路径
	public $dpath;//缩略图存放路径
	public $xlen;//缩略图长度
	public $ylen;//缩略图高度
	public $file;//$_FILES['$name']
	public function __construct($file,$opath='./upload/images/oimage/',$dpath='./upload/images/dimage/',$xlen=165,$ylen=165){
		$this->file=$file;
		$this->opath=$opath;
		$this->dpath=$dpath;
		$this->xlen=$xlen;
		$this->ylen=$ylen;
		$this->file_dispose();
	}
	public function file_dispose(){//文件处理函数
		$max_file_size=5000000;//上传文件大小限制
		$uptypes=array(//上传文件类型列表
			'image/jpg',
			'image/png',
			'image/jpeg',
			'image/gif',
			'image/bmp',
			'image/x-png'
			);
			if(!is_uploaded_file($this->file[tmp_name])){//是否存在文件
				echo '<script>alert(\'文件不存在！\')</script>';
				exit;
			}
			if($max_file_size<$this->file['size']){
				echo '<script>alert(\'文件超过限制大小！\')</script>';
				exit;
			}
			if(!in_array($this->file['type'],$uptypes)){
				echo '<script>alert(\'不允许文件类型，请确认选择的文件为图片！\')</script>';
				exit;
			}
			if(!file_exists($this->opath)){
				mkdir($this->opath);
			}
			$filename=$this->file['tmp_name'];
			$filetype=substr($this->file['name'],strrpos($this->file['name'],"."),strlen($this->file['name'])-strrpos($this->file['name'],"."));
			$destination=$this->opath.date('YmdHis').rand(0000,9999).$filetype;
			if(move_uploaded_file($filename,$destination)){
				echo '<script>alert(\'上传成功！\')</script>';
			}
			// 设置缩略图宽高
			$width = $this->xlen;
			$height = $this->ylen;


			// Get new dimensions
			list($width_orig, $height_orig) = getimagesize($destination);

			if ($width && ($width_orig < $height_orig)) {
    			$width = ($height / $height_orig) * $width_orig;
			} 
			else {
    			$height = ($width / $width_orig) * $height_orig;
			}

			// Resample
			//echo $this->file['type'];
			$image_p = imagecreatetruecolor($width, $height);
			$image = imagecreatefromjpeg($destination);
			imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
            $imagename=basename($destination);
            $_SESSION['imagename']=$imagename;
			if(!file_exists($this->dpath)){
				mkdir($this->dpath);
			}
			// Output
			imagejpeg($image_p, $this->dpath.$imagename, 100);
			
		}
		public function getImagename(){//获取文件名
			return $_SESSION['imagename'];
		}
}